package com.czk.model.ptotorype.deepclone;

import com.czk.model.ptotorype.improve.Sheep;

import java.io.*;

/**
 * 深拷贝 实现方式一
 * 通过clone的方式
 */
public class BigSheep implements Serializable,Cloneable {
    private static final long SERIALIZALEID=123456679L;
    private String name;
    private String color;
    private Sheep sheep;

    @Override
    public String toString() {
        return "BigSheep{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", sheep=" + sheep +
                '}';
    }

    public BigSheep(String name, String color, Sheep sheep) {
        this.name = name;
        this.color = color;
        this.sheep = sheep;
    }

    public static long getSERIALIZALEID() {
        return SERIALIZALEID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Sheep getSheep() {
        return sheep;
    }

    public void setSheep(Sheep sheep) {
        this.sheep = sheep;
    }

    /**
     * 深拷贝 实现方式一
     * 通过clone的方式
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        BigSheep bigSheep=null;
        //先拷贝基本数据
        bigSheep=(BigSheep) super.clone();
        //拷贝引用数据类型
        bigSheep.setSheep((Sheep)sheep.clone());
        return bigSheep;
    }

    /**
     * 深拷贝实现方式二
     * 通过序列化与反序列化的方式来实现深拷贝
     * @return
     */
    public Object deepClone(){
        ByteArrayOutputStream byteArrayOutputStream=null;
        ObjectOutputStream objectOutputStream=null;
        ByteArrayInputStream byteArrayInputStream=null;
        ObjectInputStream objectInputStream=null;
        BigSheep bigSheep=null;
        try {
            byteArrayOutputStream=new ByteArrayOutputStream();
            objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(this);
            byteArrayInputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            objectInputStream=new ObjectInputStream(byteArrayInputStream);
            bigSheep = (BigSheep) objectInputStream.readObject();

        }catch (IOException | ClassNotFoundException ex){
            ex.printStackTrace();
        }
        return bigSheep;
    }
}
